package com.plugin.sproutcore.core.resources.natures;

import java.io.IOException;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;

import com.plugin.sproutcore.core.resources.properties.PropertiesLoader;
import com.plugin.sproutcore.core.resources.properties.SproutCoreProject;
import com.plugin.sproutcore.core.resources.properties.SproutCoreProperties;
import com.plugin.sproutcore.util.ProjectUtil;
import com.plugin.sproutcore.util.SproutCoreUtil;

public class SproutCoreNature implements IProjectNature 
{
	public static final String NATURE_ID = "core.resources.natures.SproutCoreNature";
	
	private IProject project;

	public void configure() throws CoreException 
	{
		try {
			createProperties(getProject());
		} catch (IOException e) {
			IStatus status = ProjectUtil.createErrorStatus(e.getMessage());
			throw new CoreException(status);
		}
	}

	public void deconfigure() throws CoreException 
	{
		try {
			deleteProperties(getProject());
		} catch (IOException e) {
			IStatus status = ProjectUtil.createErrorStatus(e.getMessage());
			throw new CoreException(status);
		}

	}
	
	private static void createProperties(IProject project) 
	throws CoreException, IOException
	{
		if ( project != null && project.exists())
		{
			IContainer[] containers = SproutCoreUtil.getAllSproutCoreProjects(project);
			SproutCoreProperties properties = new SproutCoreProperties();
			SproutCoreProject scProject;
			for (IContainer container:containers)
			{
				scProject = SproutCoreUtil.createSproutCoreProject(container);
				properties.getScProjects().add(scProject);
			}
			PropertiesLoader.save(project, properties);
		}
	}
	
	private static void deleteProperties(IProject project) 
	throws IOException
	{
		if ( project != null && project.exists())
		{
			PropertiesLoader.delete(project);
		}
	}

	public void setProject(IProject project) {
		this.project = project;
	}
	public IProject getProject() {
		return this.project;
	}

}
